package com.zhuliwei.service.impl;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.patterns.SystemPatterns;
import com.zhuliwei.service.EmailService;
import com.zhuliwei.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.zhuliwei.constants.RabbitConstants.EMAIL_AUTHCODE_KEY;
import static com.zhuliwei.constants.RabbitConstants.EMAIL_EXCHANGE_NAME;

/**
 * 邮箱接口
 *
 * @author 朱力维
 * @time 2022/10/16 10:55
 **/
@Service
public class EmailServiceImpl implements EmailService {
    @Resource
    private RedisCache redisCache;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult getEmailAuthCode(String email) {
        // 邮箱不能为空
        if (!StringUtils.hasText(email)) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        // 邮箱格式校验
        if (!emailCheck(email)) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_CHECK_FALSE);
        }
        String authCode = generateCode();
        // 邮箱验证码存入redis 并设置有效期五分钟
        redisCache.setCacheObject(SystemConstants.EMAIL_CODE_PREFIX + email, authCode, 5, TimeUnit.MINUTES);
        // 邮件发送到用户邮箱
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("authCode", authCode);
        messageMap.put("to", email);
        rabbitTemplate.convertAndSend(EMAIL_EXCHANGE_NAME, EMAIL_AUTHCODE_KEY, messageMap);
        return ResponseResult.okResult();
    }

    private String generateCode() {
        Random random = new Random();
        String str = "";
        String s = "";
        for (int i = 0; i < 6; i++) {
            s = String.valueOf(random.nextInt(10));
            str = str.concat(s);
        }
        return str;
    }

    private Boolean emailCheck(String email) {
        if (email.matches(SystemPatterns.EMAIL_CHECK))
            return true;
        return false;
    }

}
